/**
 * Contains {@link NetworkInterface}
 */
package logic.connectors;

import java.net.Inet4Address;
import java.net.UnknownHostException;
import logic.pathelements.PathElement;

/**
 * Interface with IPv4 address
 * @author Alexey Akimov <frinatella@gmail.com>
 */
public class NetworkInterface extends Connector {
    
    /**
     * max MAC value for all ports in project
     */
    private static long lastmacAddress = 0;
    
    /**
     * this interface IPv4 address
     */
    private Inet4Address ip = null;
    
        /**
     * this port MAC
     */
    private long macAddress;
    
     /**
     * Constructor
     * 
     * Generates unique MAC for each NetworkInterface instance
     * @param owner this interface owner
     * @throws Exception if MAC range has been exceeded
     */
    public NetworkInterface(PathElement owner) throws Exception {
        super(owner);
        if (lastmacAddress == Long.MAX_VALUE) {
            throw new Exception("MAC range has been exceeded");
        }
        macAddress = ++lastmacAddress;
    }

    /**
     * Constructor
     * @param owner this interface owner
     * @param ip IPv4 address for this interface
     * @throws Exception if MAC range has been exceeded
     */
    public NetworkInterface(PathElement owner, Inet4Address ip) throws Exception {
        this(owner);
        this.ip = ip;
    }
    
    /**
     * Constructor
     * @param owner this interface owner
     * @param ip IPv4 address text representation for this interface
     * @throws Exception if MAC range has been exceeded
     */
    public NetworkInterface(PathElement owner, String ip) throws Exception {
        this(owner);
        this.ip = (Inet4Address) Inet4Address.getByName(ip);
    }
    
    /**
     * Getter
     * @return IPv4 address
     */
    public Inet4Address getIp() {
        return ip;
    }
    
    /**
     * Getter
     * @return IPv4 address text representation
     */
    public String getIpTextRepresentation() {
        return ip.getHostAddress();
    }
    
    /**
     * Getter
     * @return this port MAC
     */
    public long getmacAddress() {
        return macAddress;
    }
    
    /**
     * Setter
     * @param ip IPv4 address
     */
    public void setIp(Inet4Address ip) {
        this.ip = ip;
    }
    
    /**
     * Setter
     * @param string IPv4 address text representation
     */
    public void setIp(String ip) throws UnknownHostException {
        this.ip = (Inet4Address) Inet4Address.getByName(ip);
    }
    
}
